What is p-filter?
The p-filter npm package is a utility that allows you to filter collections of items using asynchronous predicate functions. It is particularly useful when you need to perform some asynchronous operation to determine whether an item should be included in the resulting array.
What are p-filter's main functionalities?
Asynchronous Filtering
This feature allows you to filter an array asynchronously. The `getIsAnimal` function might perform an asynchronous operation, such as fetching data from an API to determine if the name belongs to an animal. The `pFilter` function will then return a new array containing only the names that are animals.
const pFilter = require('p-filter');
const getIsAnimal = async (name) => { /* ... */ };
const names = ['Sphinx', 'Hydra', 'Human'];
const animals = await pFilter(names, getIsAnimal);
Other packages similar to p-filter
async.filter
Part of the 'async' utility module, this function offers asynchronous filtering capabilities. It is part of a larger suite of asynchronous control flow and collection processing utilities, which might make it a heavier dependency than p-filter if only filtering is needed.
bluebird
Bluebird is a comprehensive promise library that includes a method called 'filter', which can be used for asynchronous filtering. It is more feature-rich than p-filter but also larger in size, which might be an overkill for simple use cases.
p-filter
Filter promises concurrently
Useful when you need to run promise-returning & async functions multiple times with different inputs concurrently and get a filtered down result.
Install
$ npm install --save p-filter
Usage
const pFilter = require('p-filter');
const getWeather = require('get-weather');
const places = [
getCapital('Norway').then(info => info.name),
'Bangkok, Thailand',
'Berlin, Germany',
'Tokyo, Japan'
];
const filterer = el => getWeather(el).then(place => place.temperature > 30);
pFilter(places, filterer).then(result => {
console.log(result);
});
API
pFilter(input, filterer, [options])
Returns a Promise
that is fulfilled when all promises in input
and ones returned from filterer
are fulfilled, or rejects if any of the promises reject. The fulfilled value is an Array
of the fulfilled values returned from filterer
in input
order.
input
Type: Iterable<Promise|any>
Iterated over concurrently in the filterer
function.
filterer(element, index)
Type: Function
Expected to return a boolean
or a Promise
for a boolean
.
options
Type: Object
concurrency
Type: number
Default: Infinity
Number of concurrently pending promises returned by filterer
. Minimum 1
.
Related
License
MIT © Sindre Sorhus